package amazon

import (
	"encoding/json"
	"fmt"
	"gitee.com/wengo/go-mamba"
	"github.com/PuerkitoBio/goquery"
	"net/url"
	"regexp"
	"strings"
)

type Listing struct {
	amz *Amazon
}

func NewListing(amazon *Amazon) *Listing {
	return &Listing{
		amz: amazon,
	}
}

// 从Listing页面获取获取Coupon
//
// html listing页面
func (a *Amazon) GetCoupon(html string) (resp *mamba.Response, document *goquery.Document, err error) {
	matcher := regexp.MustCompile(`'&([^']+)';`)
	couponParams := matcher.FindAllStringSubmatch(html, -1)
	if len(couponParams) > 0 {
		var params = make(map[string]string)
		for _, values := range strings.Split(couponParams[0][1], "&") {
			splitParams := strings.Split(values, "=")
			params[splitParams[0]] = splitParams[1]
		}

		params["buyingOptionType"] = ""
		params["source"] = "dp_cxcw_C"

		params["anti-csrftoken-a2z"], _ = url.QueryUnescape(params["anti-csrftoken-a2z"])

		resp, document, err = a.Ajax(`/promotion/redeem/`, GET, nil, params, nil)

		return
	}

	return nil, nil, fmt.Errorf("无法获取折扣券")
}

// 从Listing页面获取跟卖
//
// html listing页面
func (a *Amazon) GetOfferListing(asin string) (resp *mamba.Response, document *goquery.Document, err error) {
	resp, document, err = a.Ajax(fmt.Sprintf(OfferListings, asin), GET, nil, nil, nil)
	return
}

// 从Listing页面获取父Asin
//
// html listing页面
func (a *Amazon) ExtractParentAsin(html string) string {
	matcher := regexp.MustCompile(`"parentAsin"\s?:\s?"([^"]+)"`)
	parentAsin := matcher.FindStringSubmatch(html)
	if len(parentAsin) > 0 {
		return parentAsin[1]
	}

	return ""
}

// 从Listing页面获取变体
func (a *Amazon) ExtractVariations(html string) map[string]string {
	matcher := regexp.MustCompile(`"dimensionToAsinMap"\s?:\s?({[^}]+})`)
	//
	//body := a.Response.String()

	value := matcher.FindStringSubmatch(html)
	var dimensionToAsinMap map[string]string
	if len(value) > 0 {
		json.Unmarshal([]byte(value[1]), &dimensionToAsinMap)
	}

	return dimensionToAsinMap

	//matcher, _ = regexp.Compile(`variationValues"\s?:\s?({.+})`)
	//variationValues := matcher.FindString(resp.String())
	//
	//matcher, _ = regexp.Compile(`asinVariationValues"\s?:\s?({.+})`)
	//asinVariationValues := matcher.FindString(resp.String())
	//
	//matcher, _ = regexp.Compile(`dimensionValuesData"\s?:\s?({.+})`)
	//dimensionValuesData := matcher.FindString(resp.String())
	//
	//matcher, _ = regexp.Compile(`asinToDimensionIndexMap"\s?:\s?({.+})`)
	//asinToDimensionIndexMap := matcher.FindString(resp.String())

}

// 检查产品可售
//
// document: 当前返回的Response
func (a *Amazon) CheckListingAvailable(document *goquery.Document) bool {
	if document.Find("#outOfStock").Length() > 0 {
		return false
	}

	return true
}

// 检查产品当前是否有购物车
//
// document: 当前返回的Response
func (a *Amazon) CheckListingHasCart(document *goquery.Document) bool {
	if document.Find("#add-to-cart-button").Length() > 0 || document.Find("#add-to-cart-button-ubb").Length() > 0 {
		return true
	}

	return false
}
